package com.example.common.mvvm.view;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;

import com.example.common.filed.DataActionEntity;
import com.example.common.mvvm.viewmodel.BaseViewModel;

import java.lang.ref.WeakReference;
import java.lang.reflect.ParameterizedType;
import java.util.Map;

public abstract class BaseFragment<V extends ViewBinding , VM extends BaseViewModel> extends Fragment implements IView {
    protected V v;
    protected VM vm;
    protected LayoutInflater inflater;
    protected BusDataObserver busDataObserver;




    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inflater = LayoutInflater.from(getContext());
        busDataObserver = new BusDataObserver(this);
        initViewModel();
        getLifecycle().addObserver(vm);
        vm.vmData.uiData.observe(this, busDataObserver);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        v = (V) initBind();
        initView();
        initData();

        return bindLayout();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getLifecycle().removeObserver(vm);
        vm.vmData.uiData.removeObserver(busDataObserver);
    }
    public abstract void receiveData(Map<String, Object> data);
    @Override
    public void initViewModel() {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        Class clazz = (Class) type.getActualTypeArguments()[1];
        vm = (VM) new ViewModelProvider(this,new ViewModelProvider.NewInstanceFactory())
                .get(clazz);
    }

    public static class BusDataObserver implements Observer<DataActionEntity> {
        private WeakReference<BaseFragment> weakReference;

        public BusDataObserver(BaseFragment baseFragment) {
            weakReference = new WeakReference<>(baseFragment);
        }

        @Override
        public void onChanged(DataActionEntity entity) {

            if (weakReference.get() == null) {
                return;
            }
            if (entity.action.equals("DATA")){
                Map<String, Object> data = entity.data;
                weakReference.get().receiveData(data);
            }

        }
    }

}
